package com.refusea.train.domain.tx.impl

import com.refusea.train.domain.entity.Referrer
import com.refusea.train.domain.entity.School
import com.refusea.train.domain.entity.User
import com.refusea.train.domain.entity.User.Role.REFERRER
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.domain.tx.RegisterTx
import com.refusea.train.mapper.ReferrerMapper
import com.refusea.train.mapper.SchoolMapper
import com.refusea.train.mapper.UserMapper
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * @author Zhang Yan 2024/3/23
 **/
@Service
@Transactional
class RegisterTxImpl(
    private val userMapper: UserMapper,
    private val schoolMapper: SchoolMapper,
    private val referrerMapper: ReferrerMapper,
) : RegisterTx {

    override fun principalRegister(user: User, school: School) {

        if (schoolMapper.insert(school) == 0) {
            throw BizEx.of("学校名已存在")
        }

        user.schoolId = school.id
        if (userMapper.insert(user) == 0) {
            throw BizEx.of("登录 ID 已存在")
        }

        schoolMapper.setPrincipal(school.id, user.id)
    }

    override fun register(user: User) {

        if (userMapper.insert(user) == 0) {
            throw BizEx.of("登录 ID 已存在")
        }

        if (user.role == REFERRER) {
            referrerMapper.insert(Referrer.defaultReferrer(user.id, user.schoolId, user.name))
        }
    }
}
